package cn.edu.csmzxy.rk233x.auth_system.service.impl;

/**
 * @author wumxing
 * @date 2025/10/15 9:51
 * @description
 */
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysRole;
import cn.edu.csmzxy.rk233x.auth_system.entity.SysUserRole;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysRoleMapper;
import cn.edu.csmzxy.rk233x.auth_system.mapper.SysUserRoleMapper;
import cn.edu.csmzxy.rk233x.auth_system.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRole> implements SysUserRoleService {
    @Autowired
    private SysUserRoleMapper userRoleMapper;
    @Autowired
    private SysRoleMapper roleMapper;
    // 根据用户ID查询角色列表
    @Override
    public List<SysRole> getRolesByUserId(Long userId) {
        // 1. 查询用户-角色关联记录
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        List<SysUserRole> userRoles = userRoleMapper.selectList(wrapper);
        if(userRoles==null || userRoles.isEmpty()) {
            return  new ArrayList<>();
        }
        // 2. 提取角色ID，查询角色详情
        List<Long> roleIds = userRoles.stream()
                .map(SysUserRole::getRoleId)
                .collect(Collectors.toList());

        return roleMapper.selectBatchIds(roleIds);
    }

    //给userId分配角色 roleIds
    @Override
    @Transactional
    public void assignRoles(Long userId, List<Long> roleIds) {
        // 先删除原有关联
        LambdaQueryWrapper<SysUserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUserRole::getUserId, userId);
        userRoleMapper.delete(wrapper);

        // 新增关联
        for (Long roleId : roleIds) {
            SysUserRole userRole = new SysUserRole();
            userRole.setUserId(userId);
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }
    }
}
